import React, { useCallback, useEffect, useState } from 'react';
import { Button, Space, Table, Tag, Dropdown, Form, Input, Select, Drawer, Modal, Popconfirm } from 'antd';
import type { TableProps, MenuProps, PopconfirmProps,DrawerProps } from 'antd';
import instance from '../../api/instance';
import { PlusOutlined, DeleteOutlined, RedoOutlined, OpenAIOutlined, SearchOutlined } from '@ant-design/icons';


interface DataType {
  key: string;
  title: string;
  viewCount: number;
  updatedAt: string;
  createdAt: string;
  tags: string[];
  content: string;
  id: number
}

type FieldType = {
  title?: string;
  content?: string;
  remember?: string;
};


const Home: React.FC = () => {
  const [tableData, setTableData] = useState<DataType[]>([])
  const [tableTotal, setTableTotal] = useState(0)
  const [page, setPage] = useState(1)
  const [pageSize, setPageSize] = useState(10)
  const [title, setTitle] = useState('')
  const [tag, setTag] = useState('')
  const [searchform] = Form.useForm();
  const [addform] = Form.useForm();
  const [open, setOpen] = useState(false);
  const [confirmLoading, setConfirmLoading] = useState(false);
  const [placement, setPlacement] = useState<DrawerProps['placement']>('right');

  const columns: TableProps<DataType>['columns'] = [
    {
      title: '序号',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '用户名',
      dataIndex: 'title',
      key: 'title',
    },
    {
      title: '手机号',
      dataIndex: 'updatedAt',
      key: 'updatedAt',
    },
    {
      title: '性别',
      dataIndex: 'viewCount',
      key: 'viewCount',
    },
    {
      title: '昵称',
      dataIndex: 'content',
      key: 'content',
    },
    {
      title: '邮箱',
      dataIndex: 'createdAt',
      key: 'createdAt',
    },
    {
      title: '用户状态',
      key: 'tags',
      dataIndex: 'tags',
      render: (_, { tags }) => (
        <>
          {tags.map((tag) => {
            let color = tag.name.length > 5 ? 'geekblue' : 'green';
            return (
              <Tag color={color} key={tag.name}>
                {tag.name.toUpperCase()}
              </Tag>
            );
          })}
        </>
      ),
    },
    {
      title: 'Action',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button>查看</Button>
          <Button>编辑</Button>
          <Popconfirm
            title="删除"
            description="确定删除吗?"
            onConfirm={() => confirm(record.id)}
            onCancel={cancel}
            okText="确定"
            cancelText="取消"
          >
            <Button danger>删除</Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const confirm = useCallback((id: number) => {
    const newData = tableData.filter(item => item.id !== id)
    setTableData(newData)
  }, [tableData])

  const cancel: PopconfirmProps['onCancel'] = (e) => {
    console.log(e);
  };

  const tableSj = () => {
    const params: {
      page: number,
      pageSize: number,
      keyword?: string,
      tag?: string
    } = { page, pageSize }
    if (title) params.keyword = title
    if (tag) params.tag = tag

    instance.get('/article/list', {
      params
    }).then(res => {
      console.log('res', res)
      if (res.data.rows) {
        setTableData(res.data.rows)
        setTableTotal(res.data.count)
      }
    })
  }
  useEffect(() => {
    tableSj()
  }, [page, pageSize, title, tag])

  //分页
  const changeTotal = (currentPage: number, currentPageSize: number) => {
    setPage(currentPage)
    setPageSize(currentPageSize)
  }

  //下拉
  const items: MenuProps['items'] = [
    {
      key: '1',
      label: '姓名'
    },
    {
      key: '2',
      label: '浏览次数'
    },
    {
      key: '3',
      label: '标签'
    },
  ];

  //查询
  const onFinish = (values) => {
    setTitle(values.title)
    setTag(values.tag)
  };
  //重置
  const cz = () => {
    searchform.resetFields()
    setTitle('')
    setTag('')
  }

  const handleChange = (value: string) => {
    console.log(`selected ${value}`);
  };

  //抽屉
  const onClose = () => {
    setOpen(false);
  };

  const handleOk = () => {
    const { content, title } = addform.getFieldsValue()
    instance.post('/article', {
      title,
      content,
      tagList: ['新增'],
      categoryList: ['分类'],
      authorId: '47529555'
    }).then((res) => {
      console.log('res', res)
      if(res.data.id){
        setOpen(false)
        tableSj()
        addform.resetFields()
        setPlacement(false)
      }
    })
  };


  const handleCancel = () => {
    console.log('Clicked cancel button');
    setOpen(false);
  };



  return (
    <div>
      <div className='mb-[20px]'>
        <Form
          name="basic"
          layout='inline'
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          onFinish={onFinish}
          form={searchform}
        >
          <Form.Item
            label="用户名"
            name="title"
          >
            <Input placeholder="请输入用户名" />
          </Form.Item>

          <Form.Item
            label="性别"
            name="viewCount"
          >
            
            <Input placeholder="请输入性别" />
          </Form.Item>

          <Form.Item
            label="昵称"
            name="content"
          >
            <Input placeholder="请输入昵称" />
          </Form.Item>

          <Form.Item
            label="手机号"
            name="updatedAt"
          >
            <Input placeholder="请输入手机号" />
          </Form.Item>

          <Form.Item
            label="邮箱"
            name="createdAt"
          >
            <Input placeholder="请输入邮箱" />
          </Form.Item>

          <Form.Item
            label="用户状态"
            name="tag"
          >
            <Input placeholder="请输入用户状态" />
          </Form.Item>

          <Form.Item label={null}>
            <Button onClick={cz}>
              <RedoOutlined />
              重置
            </Button>
          </Form.Item>

          <Form.Item label={null}>
            <Button color="primary" variant="outlined" htmlType="submit">
              <SearchOutlined />
              查询
            </Button>
          </Form.Item>
        </Form>
      </div>
      <div className='text-right'>
        <Button color="purple" variant="outlined" className='mr-[5px]' onClick={() => setOpen(true)}><PlusOutlined />新增</Button>
        <Button color="danger" variant="outlined" className='mr-[5px]'><DeleteOutlined />批量删除</Button>
        <Button className='mr-[5px]'><RedoOutlined />刷新</Button>
        <Dropdown menu={{ items }} placement="bottom">
          <Button><OpenAIOutlined />列设置</Button>
        </Dropdown>
      </div>
      <Table<DataType> columns={columns} dataSource={tableData}
        pagination={{
          total: tableTotal,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total) => `Total ${total} items`,
          onChange: changeTotal
        }}
        rowKey='id' />
      {/* 抽屉 */}
      <Drawer
        title="新增用户"
        placement={placement}
        width={500}
        onClose={onClose}
        open={open}
        extra={
          <Space>
            <Button onClick={onClose}>Cancel</Button>
            <Button type="primary" onClick={handleOk}>
              OK
            </Button>
          </Space>
        }
      >
        <Form
          name="add"
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          form={addform}
        >
          <Form.Item
            label="用户名"
            name="title"
            rules={[{ required: true, message: '用户名不能为空' }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="昵称"
            name="content"
            rules={[{ required: true, message: '昵称不能为空' }]}
          >
            <Input />
          </Form.Item>
        </Form>
      </Drawer>
     
    </div>
  )
};

export default Home;